<?php

$now = date(' c ');
$log = __DIR__ . "/../hook.log";

$config = [
    'user' => 'xuegefan',
    'pass' => 'xue520..',
    'projects' => [
        'jsxtsc' => [
            'password' => '123456',
            'branch' => 'master',
            'path' => '/www/wwwroot/doc.nanazcs.com/test',
        ],
    ],
];
header("Content-type: text/html; charset=utf-8");
$hook = json_decode(file_get_contents('php://input'), true);

if (!is_array($hook) || empty($hook)) {
    header('HTTP/1.1 304 Not Modified');
    exit;
}

error_log("[{$now}] ".$_SERVER['REMOTE_ADDR'].' '.$_SERVER['REQUEST_URI']."\r\n{".var_export($hook,true)."}\r\n", 3,$log);

$user_name = $hook['password'];
$project_url = $hook['project']['git_http_url'];
$project_branch = $hook['project']['default_branch'];

$repoUrl = 'https://'.$config['user'].':'.urlencode($config['pass']).'@'.str_replace('https://', '', $project_url);
error_log("[{$now}] ".$_SERVER['REMOTE_ADDR'].' '.$_SERVER['REQUEST_URI']."\r\n{".var_export($repoUrl,true)."}\r\n", 3,$log);
$descriptorspec = array(
   0 => array("pipe", "r"),
   1 => array("pipe", "w"),
   2 => array("pipe", "w"),
);
$process = proc_open('/usr/bin/git/bin/git pull '.$repoUrl.' '.$project_branch, $descriptorspec, $pipes, $config['projects'][$user_name]['path'], NULL);
if(is_resource($process)){
    $output = stream_get_contents($pipes[1]);
    fclose($pipes[1]);
    $output .= stream_get_contents($pipes[2]);
    fclose($pipes[2]);
}
$return_value = proc_close($process);
error_log("[{$now}] ".$_SERVER['REMOTE_ADDR'].' '.$_SERVER['REQUEST_URI']."\r\n{".var_export($output,true)."}\r\n", 3,$log);
echo 'ok';